"use client"

import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { db } from "@/db"
import { users } from "@/db/schema"
import { signIn } from "next-auth/react"
import { nanoid } from "nanoid"

// 注册表单验证模式
const signupFormSchema = z.object({
  username: z.string().min(3, {
    message: "用户名至少需要3个字符",
  }),
  email: z.string().email({
    message: "请输入有效的邮箱地址",
  }),
  password: z.string().min(6, {
    message: "密码至少需要6个字符",
  }),
})

export type SignupFormSchemaType = z.infer<typeof signupFormSchema>;

export default function Page() {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  
  const form = useForm<SignupFormSchemaType>({
    resolver: zodResolver(signupFormSchema),
    defaultValues: {
      username: "",
      email: "",
      password: ""
    }
  })

  // 处理表单提交
  async function onSubmit(values: SignupFormSchemaType) {
    setIsLoading(true);
    setError(null);

    try {
      // 创建用户
      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          email: values.email,
          password: values.password,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || '注册失败');
      }

      // 注册成功后自动登录
      const result = await signIn("credentials", {
        username: values.username,
        password: values.password,
        redirect: false,
      });

      if (result?.error) {
        setError(result.error);
        return;
      }

      // 登录成功，跳转到首页
      router.push("/");
    } catch (error: any) {
      setError(error.message || '注册过程中发生错误');
    } finally {
      setIsLoading(false);
    }
  }

  return <div className='py-[100px] w-full bg-gradient-to-br from-lime-400 to-cyan-400 h-screen flex items-center justify-center'>
    <Form {...form}>
      <div>
        <form
          className="p-[20px] w-[420px]"
          onSubmit={form.handleSubmit(onSubmit)}
        >
          <Card className="w-[350px]">
            <CardHeader>
              <CardTitle>注册账号</CardTitle>
              <CardDescription>创建一个新账号以使用系统</CardDescription>
            </CardHeader>
            <CardContent>
              {error && (
                <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                  {error}
                </div>
              )}
              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem className="mb-4">
                    <FormLabel>用户名</FormLabel>
                    <FormControl>
                      <Input placeholder="请输入用户名" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem className="mb-4">
                    <FormLabel>邮箱</FormLabel>
                    <FormControl>
                      <Input placeholder="请输入邮箱" type="email" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>密码</FormLabel>
                    <FormControl>
                      <Input placeholder="请输入密码" type="password" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </CardContent>
            <CardFooter>
              <div className='flex w-full flex-col gap-2'>
                <Button size='lg' className='w-full' type="submit" disabled={isLoading}>
                  {isLoading ? "注册中..." : "注册"}
                </Button>
                <div className="text-center text-sm">
                  已有账号？<a href="/sign-in" className="text-blue-600 hover:underline">登录</a>
                </div>
              </div>
            </CardFooter>
          </Card>
        </form>
      </div>
    </Form>
  </div>
}